package com.lpf.nio2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Nio2Server {

    public AsynchronousServerSocketChannel assoc;

    void listen() throws IOException {
        //1. 创建一个线程池,用来执行来自内核的回调请求
        ExecutorService threadPool = Executors.newCachedThreadPool();
        //2. 创建异步通道群组，并绑定线程池
        AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withCachedThreadPool(threadPool, 1);
        //3. 创建服务端异步通道，并绑定到 AsynchronousChannelGroup
        assoc = AsynchronousServerSocketChannel.open(channelGroup);
        //4. 绑定监听端口
        assoc.bind(new InetSocketAddress(8080));
        //5. 监听连接，并传入回调类去处理连接请求
        assoc.accept(this, new AcceptHandler());
    }
}